using System.Collections.Generic;
using ViScript.Core.ParsedSentence;

namespace ViScript.Core
{
    public interface IParsedSentenceBuilder
    {
        void Build(IParsedSentence parsedSentence);
        IParsedSentence Result { get; }
    }

    public class ParsedSentenceBuilder : IParsedSentenceBuilder
    {
        private readonly ISentence sentence;
        private readonly List<IParsedSentence> parsedSentences = new List<IParsedSentence>();
        private IParsedSentence result = null;
        private bool isAmbiguous = false;

        public ParsedSentenceBuilder(ISentence sentence)
        {
            this.sentence = sentence;
        }

        public void Build(IParsedSentence parsedSentence)
        {
            if (parsedSentence.IsValid)
            {
                if (result == null)
                {
                    result = parsedSentence;
                }
                else
                {
                    isAmbiguous = true;
                }
            }
        }

        public IParsedSentence Result
        {
            get
            {
                if (result == null)
                {
                    return new UnrecognizedParsedSentence(sentence, parsedSentences.ToArray());
                }
                if (isAmbiguous)
                {
                    return new AmbiguousParsedSentence(sentence, parsedSentences.ToArray());
                }
                return result;
            }
        }
    }
}